<template>
  <div id="app">
    <div v-show="!UserAccount.get('id')">
      <p>
        <input
          type="text"
          v-model="name"
        >
      </p>
      <p>
        <input
          type="password"
          v-model="password"
        >
      </p>
      <p>
        <button
          @click="login"
          type="button"
        >登录</button>
      </p>
    </div>
    <div v-if="UserAccount.get('id')">
      <p>
        你好，{{UserAccount.get('nickname')}}({{UserAccount.get('role')}})
        <button @click="logout">退出</button>
      </p>
      todo：
      <ul>
        <li
          v-for="item in UserAccount.get('todo_list')"
          :key="item.id"
        >
          {{item.id}}:
          {{item.title}}
          {{item.content}}
        </li>
        <li><input
            type="text"
            placeholder="标题"
            v-model="title"
          ><input
            type="text"
            placeholder="内容"
            v-model="content"
          ><button
            @click="addTodo"
            type="button"
          >提交</button></li>
      </ul>
    </div>
  </div>
</template>

<script>
  import HelloWorld from "./components/HelloWorld.vue";
  import queryLogin, { UserAccount, getDetail, logout } from "@/gql/user";
  import { runInAction } from "mobx";
  import gql from "graphql-tag";
  import axios from "axios";
  import { Observer } from "mobx-vue";
  export default Observer({
    name: "app",
    components: {
      HelloWorld
    },
    data() {
      return {
        UserAccount,
        name: "",
        password: "",
        title: "",
        content: ""
      };
    },
    methods: {
      /** 加入todo */
      async addTodo() {
        if (!this.UserAccount.get("id")) return;
        let mutation = gql`
          mutation addTodo($title: bpchar!, $content: String!, $user_id: Int!) {
            insert_todo(
              objects: { title: $title, content: $content, user_id: $user_id }
            ) {
              affected_rows
              returning {
                id
              }
            }
          }
        `;
        const { data } = await this.$apollo.mutate({
          mutation,
          variables: {
            title: this.title,
            content: this.content,
            user_id: this.UserAccount.get("id")
          },
          update: (store, { data: { insert_todo } }) => {
            if (insert_todo) {
              runInAction(() => {
                this.UserAccount.set("todo_list", [
                  ...this.UserAccount.get("todo_list"),
                  {
                    __typename: insert_todo.returning[0].__typename,
                    id: insert_todo.returning[0].id,
                    title: this.title,
                    content: this.content,
                    user_id: this.UserAccount.get("id")
                  }
                ]);
              });
            }
          }
        });
      },
      /** 登录 */
      async login() {
        const account = await queryLogin({
          name: this.name,
          password: this.password
        });
        if (account) {
          // 登录成功
          console.log("登录成功");
          this.getToken(account);
        }
      },
      logout() {
        logout();
      },
      /** 获取token */
      async getToken(account) {
        const { data } = await axios.post(
          "https://34537528.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/jwt/jwt/",
          {
            "https://hasura.io/jwt/claims": {
              "x-hasura-allowed-roles": ["user", "admin"],
              "x-hasura-default-role": account.role,
              "x-hasura-user-id": String(account.id)
            }
          }
        );
        localStorage.setItem("apollo-token", data.token);
        setTimeout(() => {
          this.queryUser();
        }, 1000);
      },
      /** 登录成功后的查询 */
      async queryUser() {
        await getDetail();
      }
    },
    mounted() {
      getDetail();
    }
  });
</script>

<style>
  #app {
    font-family: "Avenir", Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #2c3e50;
    margin: 60px;
  }
</style>
